package com.fzl.spring_chatroom.utils;

import ch.qos.logback.core.util.StringUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Map;
@Slf4j
public class JwtUtils {

    private static String SECRET_STRING = "0JarXh6aN+ZqOX2AC0KYNWmNuYyG+Ig9Jmy/HgVYVEA=";

    //private static Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_STRING));
    private static Key key= Keys.hmacShaKeyFor(SECRET_STRING.getBytes(StandardCharsets.UTF_8));

    public static String genToken(Map<String, Object> claims){
        String jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .signWith(key)
                .compact();
        return jwtBuilder;

    }

    public static Claims parseToken(String token){
        if(!StringUtils.hasLength(token)){
            return null;
        }
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims=null;
        try{
            claims=build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("token解析失败:"+token);
        }
        return claims;
    }


}